<?php
error_reporting(E_ALL ^E_NOTICE);
ini_set("display_errors",1);

define('AllForTrees_Path', '/plugins/AllForTrees/');
define('AllForTrees_URL', AllForTrees_Path . 'main.php');
define('AllForTrees_Version', '3.22');
define('AllForTrees_Version_Date', '2013-06-29');
define('REQ_VER_PARSER', '22303');
define('AllForTreesBotpath', str_replace("\\", "/", getcwd()) . AllForTrees_Path);

global $vWorldTime;
#$vWorldTime = file_get_contents(F("worldtime.txt"));

global $icons;
$icons['water']    = 'file://' . AllForTreesBotpath . 'img/wateringcan_icon24x24.png';
$icons['sell']     = 'file://' . AllForTreesBotpath . 'img/consume_allcoins_icon24x24.png';
$icons['place']    = 'file://' . AllForTreesBotpath . 'img/bldg_mysteryseedling_icon24x24.png';
$icons['store']    = 'file://' . AllForTreesBotpath . 'img/building_barn_red_icon24x24.png';
$icons['waterOff'] = 'file://' . AllForTreesBotpath . 'img/wateringcan_icon24x24off.png';
$icons['sellOff']  = 'file://' . AllForTreesBotpath . 'img/consume_allcoins_icon24x24off.png';
$icons['placeOff'] = 'file://' . AllForTreesBotpath . 'img/bldg_mysteryseedling_icon24x24off.png';
$icons['storeOff'] = 'file://' . AllForTreesBotpath . 'img/building_barn_red_icon24x24off.png';

global $storageID;
$storageID = array(
	'farm' => -2,
	'england' => -8,
	'fisherman' => -9,
	'winterwonderland' => -10,
	'hawaii' => -11,
);
include_once(AllForTrees_Path . 'functions.php');

function AllForTrees_init() {
    global $hooks;
    global $this_plugin;
    $hooks['after_load_settings'] = 'AllForTrees_doWork';
    echo "Loaded AllForTrees v" . AllForTrees_Version . " by invasive/KolbHans\r\n";

}
function AllForTrees_form() {
	if (strlen($_GET['faction']) > 0){ 
		include_once(AllForTrees_Path .'data.php');	
		exit; // can we exit here? I think so!
	} elseif ($_GET['tree']) {
		include_once(AllForTrees_Path .'treeinfo.php');
		exit;
	} elseif ($_GET['reloadMap']) {
		include_once(AllForTrees_Path .'map.php');
		exit;
	} elseif (array_key_exists('saveConf',$_GET)) {
		include_once(AllForTrees_Path .'saveconf.php');
		exit;
	}	else {
		list($userId, , ,, , , ) = explode(';', file_get_contents(F('params.txt')));
		@list($level, $gold, $cash, $sizeX, $sizeY, $firstname, $locale) = explode(';', @file_get_contents(F('playerinfo.txt')));
		$vWorldtype   = file_get_contents(F('worldtype.txt'));
		global $mastery_counters, $mastery_levels;
		$mastery_counters  =  @unserialize(@file_get_contents(F('cropmastery.txt')));
		$mastery_levels    =  @unserialize(@file_get_contents(F('cropmasterycount.txt')));
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery-ui.css">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,700,400italic,700italic|Roboto+Condensed:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<style type="text/css">
body {
	color: black;
	font-size: 11px;
	font-style: normal;
	text-decoration: none;
}
body, input, button, ul, li, select, a, div, td, span { 	font-family: Roboto, Arial, sans-serif; }
table.blind td, table.grid table td { border:none !important;}
table.grid {border-collapse:collapse;}
table.grid td, table.grid th {
 border-collapse:collapse;
 border: 1px solid #c0c0c0;
 padding:2px; 
 text-align:center;
 font-family:'Roboto Condensed';
 font-size:12px;
}
table.grid th { background-color:#f0f0ff; }
table.inner { border:none !important; }

table.settings td { border-top:1px solid gray; border-bottom:1px solid gray; vertical-align:top;text-align:right;}
table.settings td:first-child {text-align:left;}
table.settingsPart td {border:none}

input[type="text"], select { border:1px solid gray; }

form#pageform {
	border-bottom:1px solid gray;
	margin:0;
	padding:0;
}
form#pageform input {
	border:1px solid gray;
	padding:2px 4px;
	margin-bottom:-1px;
}

form#pageform input.fpageActive {
	padding-top:8px;
	border-bottom:1px solid white !important;
	background:white;
}


input.fpage { background-color:#e0e0ff; }
input.fpageActive { border:2px outset blue; }

caption {
	text-align:left;
	font-weight:bold;
	font-size:15px;
	margin:4px 0px;
	padding:8px;
	background-color:#202050;
	color:white;
}
caption p {
	font-weight:normal;
	font-size:11px;
}

table {
	border-width: 1px;
	border-spacing: 2px;
	border-style: none;
	border-color: gray;
	border-collapse: collapse;
	background-color: white;
}
table th {
	border-width: 0px;
	padding: 0px;
	border-style: inset;
	border-color: gray;
	background-color: rgb(250, 240, 230);
	color: black;
	font-family: Tahoma, Arial, serif;
	font-style: normal;
	text-decoration: none;	

}
table td {
	border-width: 0px;
	padding: 0px;
	border-style: solid;
	border-color: gray;
	background-color: rgb(250, 240, 230);
	color: black;
	font-family: Tahoma, Arial, serif;
	font-style: normal;
	text-decoration: none;	

}
td.notzero, td.notzero td {
	background-color:#f0fff0;
}
div.masProgress { height:6px; }
div#saveRequestsContainer {
    border: 1px solid;
    padding:10px;
	position:absolute;
	right:100px;
	top:8px;
	display:none;
	width:200px;
}
div#saveRequestsContainer div { font-size:8px; width:100%; height:20px; overflow:hidden; }


.success {  color: #4F8A10; background-color: #DFF2BF; }
.warning {  color: #9F6000; background-color: #FEEFB3; }

div.maintable {
	position:absolute;
	left:8px;
	top:0px;
	right:316px;
	bottom:0px;
	overflow:auto;
}
div.maintable table { margin-left:auto; margin-right:auto; }
div.settings {
	position:absolute;
	top:0px;
	right:8px;
	bottom:0px;
	overflow:auto;
	width:300px;
	background-color:#f0f0f0;
}
td[count] { white-space:nowrap; }
img.icon { width:24px; height:24px; padding:4px; vertical-align:middle; }
img.on { padding:2px; border:2px solid #80c080; background-color:#e8e8e8; }
tr.mastered td { background-color:#b0ff80; }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
<script src="sorttable.js"></script>		
<script src="jquery.tablesorter.min.js"></script>		
<script language="javascript" defer="false">
var cbkont;
var rQueue = new Array();
var xhr = new Array();

function procReq() { // process next pending  request
	fSR(); // update indicator
	if (xhr.length) return; // do not start parallel requests
	if (! rQueue.length) return; // quit processing if there is no request left in queue
	var URL = rQueue[0];
	$('#saveRequestsContainer div').html(URL);
	xhr.push($.get(URL,function() { // process request
			$('#saveRequestsContainer div').html('');
			rQueue.shift();
			xhr.shift();
			procReq(); // after returning, process next request(s)
		})
	);
}
function fAction(vURL,vlue) {
	var file = "<?php echo AllForTrees_URL;?>?";

	if (vlue=='cbc') {
		cbcheck();
		vlue=cbkont;
	}
	
	if (typeof(vlue) == "undefined") {
		vlue='';
	}
	
	vURL=file+vURL+vlue+dummy();

	rQueue.push(vURL);
	procReq();
}

function actionconf(vURL) {
	if (confirm('Are you sure to proceed?')){
		fAction(vURL,'');
	}
}
function fSR() {
	var saveRequests = rQueue.length;
	$('#saveRequests').html(saveRequests);
	if (saveRequests > 0) {
		$('#saveRequestsContainer').attr("class","warning").stop().show();
		
	} else {
		$('#saveRequestsContainer').attr("class","success").fadeOut(1000);
	}
}

function cbcheck(){
	var output='';
	if (document.cb.chkbx.checked) output= 'ok';
	cbkont= output;
}

function dummy() {
	return "&"+Math.floor(Math.random()*1000001);
}

var i=1;
function point_it(event){
	var imgH = document.getElementById("map").height;
	var imgW = document.getElementById("map").width;
	pos_x = event.offsetX?(event.offsetX):event.pageX-document.getElementById("map").offsetLeft;
	pos_y = event.offsetY?(event.offsetY):event.pageY-document.getElementById("map").offsetTop;
	pos_y = imgH - pos_y;
	pos_x = Math.round((pos_x * <?= $sizeX ?>) / imgW);
	pos_y = Math.round((pos_y * <?= $sizeY ?>) / imgH);
	
	if (i++ % 2 ) {
		document.sections.x2.value = pos_x;
		document.sections.y2.value = pos_y;
	} else {
		document.sections.x1.value = pos_x;
		document.sections.y1.value = pos_y;
	}
}

function aftInfo(tree) {
//	alert("Request Info for '"+tree+"' tree!");
	$('#infoContainer').dialog().html("Loading, please wait...").show();
	$('#infoContainer').load("<?=AllForTrees_Path?>main.php?tree="+tree+dummy());
	return 1;
}

function saveConf(el) {
	var name = $(el).attr("name");
	var val = $(el).is(":checkbox")
		? ($(el).is(":checked")?'true':'false')
		: $(el).val();
		
	fAction("saveConf&name="+encodeURIComponent(name)+"&val="+encodeURIComponent(val));
}

$(document).ready(function() {
	$('.masProgress').each(function(id,el) {
		$(el).progressbar({
			value:$(el).data("value")
		});
	});
	
	$('table#trees td.colorme[count!="0"]').addClass('notzero');
	
	$('.saveConf').change(function() {
		saveConf(this);
	});
	
	$('img.icon').click(function(ev) {
		var el=ev.delegateTarget;
		var code=$(el).closest('tr').attr('tree');
		
		var action = $(el).attr('action');
		var value = $(el).attr('title');
		if ($(el).hasClass("on")) {
			$(el).removeClass("on");
			var src = $(el).attr('src');
			$(el).attr('src',src.replace(/\.png$/,"off.png"));
			// set to "select"
			fAction('faction='+action+'&code='+encodeURIComponent(code)+'&val=','select');
		} else {
			$(el).addClass("on");
			$(el).siblings("img.on").each(function(i,e) {
				var src = $(e).attr("src");
				$(e).attr('src',src.replace(/\.png$/,"off.png"));
			});
			$(el).siblings("img.on").removeClass("on");
			var src = $(el).attr('src');
			$(el).attr('src',src.replace(/off\.png$/,".png"));
			
			fAction('faction='+action+'&code='+encodeURIComponent(code)+'&val=',value);
			// set to "el.title"
			// set count to -1 if empty
			if (action == 'actionSeed') {
				var cnt = $(el).siblings("input[type=text]").first();
				if ($(cnt).val() == 0) {
					$(cnt).val("-1");
					$(cnt).change();
				}
			}
		}
	});
});

</script>
</head>

<body>
	<img src="/world_<?=$vWorldtype?>.png" style="float:left;width:53px;height:40px;padding-right:8px;">
<?php echo Parser_HTML_StatusBar(); 
	global $vWorldTime;
?>
	AllForTrees by invasive, v<?= AllForTrees_Version ?> enhanced by KolbHans. Farm: <b><?=$vWorldtype?></b>, Farmville time: <?=date("Y-m-d H:i:s",$vWorldTime)?>
	<hr>
	<form id="pageform" action="main.php" method="get" name="page">
<?php
		$vSettings = array();
		$vSettings = AFT_load('settings');
		$vpage = $vSettings['p'];

		if ( strlen($_GET['fpage'])> 0)  $vpage=$_GET['fpage']; 
		$vSettings['p']=$vpage;
		AFT_save($vSettings, 'settings');

		foreach (array("Map", "Trees", "Seeds", "Orchards", "Giftbox", "Storage", "Breeder", "Settings") as $fpage) {
			echo "<input name=\"fpage\" type=\"submit\" value=\"$fpage\" class=\"fpage".($fpage == $vpage?" fpageActive":"")."\">&nbsp;";
		}
?>
<input type="checkbox" class="saveConf" name="settings-AFT_enabled" <?php echo $vSettings['AFT_enabled']?"checked=\"checked\"":""; ?> >
AllForTrees enabled
<input type="checkbox" class="saveConf" name="settings-Breeding_enabled" <?php echo $vSettings['Breeding_enabled']?"checked=\"checked\"":""; ?> >
Breeding enabled

	</form>

	<div id="main" style="position:absolute;top:125px;left:0px;right:0px;bottom:0px;overflow:auto;padding:8px;">
<?php 	include_once(AllForTrees_Path .$vpage.'.php'); ?>
	</div>

	<div id="infoContainer" style="display:none;">InfoContainer</div>
	<div id="saveRequestsContainer">
		SAVING! <span id="saveRequests">?</span> parameter(s) left to save.
		<div></div>
	</div>

	</body>
</html>
<?php
	}
}

function AllForTrees_doWork() {
	if (!is_dir(AllForTreesBotpath.'data')) {
		AddLog2("AllForTrees migrating to data directory ".AllForTreesBotpath.'data');
		mkdir(AllForTreesBotpath.'data',0777, TRUE);
		if ($dir = opendir(AllForTreesBotpath)) {
			while(false !== ( $file = readdir($dir)) ) { 
				if (preg_match('/(\.json|_Map.png)$/',$file)) {
					AddLog2("Move $file to data ...");
					copy(AllForTreesBotpath . $file, AllForTreesBotpath."data/$file"); 
					if (file_exists(AllForTreesBotpath."data/$file")) unlink (AllForTreesBotpath . $file);
				} 
			}
			closedir($dir);
		}
	}


    $vSettings = AFT_load('settings');
	if ($vSettings['AFT_enabled']) {
		AddLog2("AllForTrees V". AllForTrees_Version ." starting...");
	} else {
		AddLog2("AllForTrees V". AllForTrees_Version ." disabled.");
		return;
	}

	if (strlen($vSettings['seed_x2'])==0){
		$vSettings['seed_x1']=0;
		$vSettings['seed_x2']=45;
		$vSettings['seed_y1']=0;
		$vSettings['seed_y2']=45;
		AFT_save($vSettings, 'settings');
	}
	
	AddLog2("AllForTrees -> loading trees");
	global $vAllTrees;
	$vAllTrees = AFT_MakeTreeDB('all');

	AllForTrees_Sell();
	AllForTrees_PlaceSeedlings();
	AllForTrees_SeedsSell();
	AllForTrees_Watering();
	AllForTrees_GBTreeSell();  // sell trees from GiftBox
	AllForTrees_StorageTreeSell();
	AllForTrees_GBTreePlace();
	AllForTrees_StorageTreePlace();	
	AllForTrees_Remove();   // Place trees from orchards
	AllForTrees_Transport();  // Transporttrees to other farm
	AllForTrees_ToOrch();   // move trees to orchards
	AllForTrees_Breeder();  // breed trees
	AllForTrees_Remove();   // Place trees from orchards

/*  Breeding yields seedlings and watering cans */
	AllForTrees_PlaceSeedlings();
	AllForTrees_SeedsSell();
	AllForTrees_Watering();
/* -------------------------------------------- */	
	
	AllForTrees_ToOrch();   // move trees to orchards
	AllForTrees_ToStorage();   // move trees to storage
	AllForTrees_Sell();
	AllForTrees_Move();
	AddLog2("AllForTrees -> --- finished work ---");
}

?>
